package com.ybwh.springboot1.service;

import com.ybwh.datasource.refreshable.druid.DruidRefreshDataSource;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.sql.SQLException;

/**
 * <p>
 * 配合配置中心刷新数据源的服务类示例
 * </p>
 *
 * @author fanbeibei
 * @version V1.0
 * @since 2019/4/6 17:42
 */

@Service
public class DataSourceRefreshService implements ApplicationContextAware {
//    @Value("${datasource.druid.url}")
    private String url;
//    @Value("${datasource.druid.username}")
    private String username;
//    @Value("${datasource.druid.password}")
    private String password;
//    @Value("${datasource.druid.driver-class-name}")
    private String driverClassName;


    private ApplicationContext context;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }


    /**
     * 刷新数据源,用于配置中心配置发生变化时回调逻辑
     *
     * @throws SQLException
     */
    public void refreshDataSource() throws SQLException {

        DruidRefreshDataSource dataSource = context.getBean(DruidRefreshDataSource.class);

        dataSource.getProperties().setUrl(url);
        dataSource.getProperties().setUsername(username);
        dataSource.getProperties().setPassword(password);
        dataSource.getProperties().setDriverClassName(driverClassName);
        dataSource.refresh();
    }
}
